package com.pachong.android.frameworkbase.customviews;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 可以伸缩的ImageView，前提是图片不变形
 * 不同于ImageView 的ScaleType， ImageView等比例变化之后ImageView的某条边不会变。
 *
 */
public class ResizableImageView extends ImageView {

	private ResizableSide mResizableSide = ResizableSide.HEIGHT; // 高度可以伸缩，以为着宽度是不变的。

	public ResizableImageView(Context paramContext) {
		super(paramContext);
	}


	public ResizableImageView(Context paramContext, AttributeSet paramAttributeSet) {
		super(paramContext, paramAttributeSet);
	}


	protected void onMeasure(int messureWidth, int messureHeight) {
		Drawable localDrawable = getDrawable();
		if (localDrawable != null) {
			float drawRate = localDrawable.getIntrinsicHeight() * 1.0f / localDrawable.getIntrinsicWidth();
			float imgViewRate = MeasureSpec.getSize(messureWidth) * 1.0f
					/ MeasureSpec.getSize(messureHeight);
//			Log.e("vivi", "drawRate == " + drawRate + "  " + imgViewRate);

			int width = 0;
			int height = 0;

			if(mResizableSide == ResizableSide.WIDTH) {
				height = MeasureSpec.getSize(messureHeight);
				width = (int) Math.ceil(height*1.0f / drawRate);
			} else if(mResizableSide == ResizableSide.HEIGHT){
				width = MeasureSpec.getSize(messureWidth);
				height = (int) Math.ceil(width * drawRate);
			}


//			if (drawRate > imgViewRate) {
//				height = View.MeasureSpec.getSize(messureHeight);
//				width = (int) Math.ceil(height*1.0f / drawRate);
//			} else {
//				width = View.MeasureSpec.getSize(messureWidth);
//				height = (int) Math.ceil(width * drawRate);
//
//			}
//			Log.e("vivi", "width == " + width + "   height == " + height);
			setMeasuredDimension(width, height);

			return;
		}
		super.onMeasure(messureWidth, messureHeight);
	}


	public void setResizableSide (ResizableSide side) {
		if(mResizableSide != side) {
			mResizableSide = side;
		}
	}

	// 可伸缩的“边”
	public enum ResizableSide {WIDTH, HEIGHT}
}
